<template>
  <div class='setmeal'>
    <!-- 输入框 -->
    <el-row :gutter="20">
      <el-col :span="4">
        <el-input v-model="searchSetmealVo.setmealName" placeholder="请输入套餐名称"></el-input>
      </el-col>
      <el-col :span="4">
        <el-select v-model="searchSetmealVo.status" placeholder="请选择套餐状态">
          <el-option v-for="item in SetmealStatus" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select v-model="searchSetmealVo.categoryId" placeholder="请选择套餐分类">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName" :value="item.id">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="3" style="text-align: left">
        <el-button type="primary" @click="searchSetmealByConditions(true)" icon="el-icon-search">查询</el-button>
      </el-col>
      <el-col :span="6" style="text-align: right">
        <el-button type="text" @click="batchUpdateStatus(1)" style="color: #67c23a">批量启售</el-button>
        <el-button type="text" @click="batchUpdateStatus(2)" style="color: #e6a23c">批量停售</el-button>
        <el-button type="text" @click="batchDel" style="color: #f56c6c;">批量删除</el-button>
      </el-col>
      <el-col :span="3" style="text-align: right">
        <el-button type="primary" @click="addOrEditSetmeal(true)" icon="el-icon-plus">添加套餐</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table ref="dishTable" :data="setmealList" stripe style="width: 100%" height="550" v-loading="loading"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center">
      </el-table-column>
      <el-table-column type="index" width="50" align="center" label="序号">
      </el-table-column>
      <el-table-column prop="setmealName" label="套餐名称" width="120" align="center">
      </el-table-column>
      <el-table-column prop="image" label="图片" width="120" align="center">
        <template slot-scope="image">
          <el-image style="width: 80px; height: 80px" :src="image.row.image" :fit="fit"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="categoryId" label="套餐分类" width="120" align="center">
      </el-table-column>
      <el-table-column prop="price" label="售价" width="120" align="center">
      </el-table-column>
      <el-table-column prop="status" label="售卖状态" width="120" align="center">
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="120" align="center">
      </el-table-column>
      <el-table-column prop="createUser" label="创建人" width="120" align="center">
      </el-table-column>
      <el-table-column prop="createDate" label="创建时间" width="200" align="center">
      </el-table-column>
      <el-table-column prop="updateUser" label="修改人" width="120" align="center">
      </el-table-column>
      <el-table-column prop="updateDate" label="修改时间" width="200" align="center">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="210" align="center">
        <template slot-scope="scope">
          <el-button @click="checkSetmeal(scope.row.id)" type="text" size="small" style="color: #67c23a;"><i
              class="el-icon-view"></i>查看</el-button>
          <el-button type="text" @click="updateStatus(scope.row)" size="small" style="color: #909399">
            <i class="el-icon-arrow-down" v-if="scope.row.status === '启售'"></i><i v-else class="el-icon-arrow-up" v></i>
            {{ scope.row.status === '启售' ? '停售' : '启售'}}</el-button>
          <el-button type="text" @click="addOrEditSetmeal(false,scope.row.id)" size="small"><i
              class="el-icon-edit"></i>编辑</el-button>
          <el-button type="text" @click="delSetmeal(scope.row.id)" size="small" style="color: #f56c6c;"><i
              class="el-icon-delete"></i>删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :page-sizes="[15, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="dataSize" align="center">
    </el-pagination>
    <!-- 查看套餐信息 -->
    <el-dialog title="套餐信息" :visible.sync="checkSetmealVisible" :before-close="cancelCheckSetmeal">
      <el-descriptions column="1" border>
        <el-descriptions-item label="套餐名称">{{ SetmealBasicDto.setmealName }}</el-descriptions-item>
        <el-descriptions-item label="图片">
          <el-image style="width: 80px; height: 80px; margin-right: 10px;" :src="item" :fit="fit" v-for="(item, index) in SetmealBasicDto.image" :key="index"></el-image>
          </el-descriptions-item>
        <el-descriptions-item label="套餐分类">{{ SetmealBasicDto.categoryId }}</el-descriptions-item>
        <el-descriptions-item label="售价">{{ SetmealBasicDto.price }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ SetmealBasicDto.sort }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ SetmealBasicDto.createUser }}</el-descriptions-item>
        <el-descriptions-item label="修改人">{{ SetmealBasicDto.updateUser }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ SetmealBasicDto.createDate }}</el-descriptions-item>
        <el-descriptions-item label="修改时间">{{ SetmealBasicDto.updateDate }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ SetmealBasicDto.description }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import request from '@/utils/request'

export default {
  name: 'UserIndex',
  // import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
  // 这里存放数据
    return {
      loading: true,
      fit: 'fill',
      baseSetmeal: '/setmeal-basic',
      pageIndex: 1,
      pageSize: 15,
      dataSize: 0,
      // 查看菜品详细信息显示状态
      checkSetmealVisible: false,
      // 套餐状态
      SetmealStatus: [
        {
          value: 1,
          label: '启售'
        },
        {
          value: 2,
          label: '停售'
        }
      ],
      // 查询套餐参数对象
      searchSetmealVo: {
        setmealName: '',
        status: '',
        categoryId: ''
      },
      // 套餐输出对象
      SetmealBasicDto: {
        id: 0,
        setmealName: '',
        categoryId: '',
        price: 0,
        image: '',
        status: 0,
        description: '',
        dishBasicDtos: [],
        sort: 0,
        createUser: '',
        createDate: new Date(),
        updateUser: '',
        updateDate: new Date(),
        isDeleted: false
      },
      // 套餐列表
      setmealList: [],
      categoryList: [],
      // 被选中的套餐列表
      setmealSelection: []
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    setmealList: {
      deep: true,
      immediate: true,
      handler (newSetmealList) {
        newSetmealList = newSetmealList.forEach(item => {
          item.status = this.changeStatus(item.status)
          item.categoryId = this.changeCategory(item.categoryId)
          if (item.image !== '') {
            item.image = item.image.split(',')[0]
          }
        })
      }
    },
    SetmealBasicDto: {
      deep: true,
      immediate: true,
      handler (SetmealBasicDto) {
        SetmealBasicDto.image = SetmealBasicDto.image.split(',')
        SetmealBasicDto.categoryId = this.changeCategory(SetmealBasicDto.categoryId)
      }
    }
  },
  // 方法集合
  methods: {
    // 根据条件查询套餐列表
    async searchSetmealByConditions (flag) {
      this.searchSetmealVo.status = this.searchSetmealVo.status === '' ? 0 : this.searchSetmealVo.status
      this.searchSetmealVo.categoryId = this.searchSetmealVo.categoryId === '' ? 0 : this.searchSetmealVo.categoryId
      // 执行查询套餐操作
      await request({
        url: this.baseSetmeal + `/setmeal-list/${this.pageIndex}/${this.pageSize}`,
        method: 'get',
        params: this.searchSetmealVo
      }).then(result => {
        this.setmealList = result.data.data.data
        this.dataSize = result.data.data.size
        this.loading = false
        if (flag) {
          this.$message({
            message: '查询成功',
            type: 'success'
          })
        }
        // 清除查询输入框数据
        this.searchSetmealVo = {}
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '查询失败'
        })
      })
    },
    // 按分类类型查询分类列表
    async searchCategoryListByType () {
      await request({
        url: '/category-basic/category-list/1/1000',
        method: 'get',
        params: {
          type: 2
        }
      }).then(result => {
        this.categoryList = result.data.data.data
      })
    },
    // 获取选中的套餐数据
    handleSelectionChange (val) {
      this.setmealSelection = val
      const ids = []
      this.setmealSelection.forEach(item => {
        ids.push(item.id)
        return item
      })
      this.setmealSelection = ids
    },
    // 跳转添加套餐界面
    addOrEditSetmeal (flag, id) {
      // 跳转到添加界面
      this.$router.push({
        name: 'addOrEditSetmeal',
        params: {
          flag,
          id
        }
      })
    },
    // 查看套餐详情
    checkSetmeal (id) {
      this.checkSetmealVisible = true
      request({
        url: this.baseSetmeal + `/setmeal-basic/${id}`,
        method: 'get'
      }).then(res => {
        if (res.data.data != null) {
          this.SetmealBasicDto = res.data.data
        } else {
          this.$message({
            message: '查看菜品失败',
            type: 'error'
          })
        }
      }).catch(err => {
        console.log(err)
        this.$message({
          message: '回显失败',
          type: 'error'
        })
      })
    },
    // 取消查看套餐详情
    cancelCheckSetmeal () {
      this.checkSetmealVisible = false
      // this.$message({
      //   message: '取消成功',
      //   type: 'info'
      // })
    },
    /**
     * 批量操作（启售、停售、删除）
     */
    // 批量上下架
    batchUpdateStatus (type) {
      let msg = ''
      if (type === 1) {
        msg = '套餐批量上架成功'
      } else {
        msg = '套餐批量下架成功'
      }
      request({
        url: this.baseSetmeal + `/status-list/${type}`,
        method: 'put',
        data: this.setmealSelection
      }).then(res => {
        if (res.data.data) {
          this.searchSetmealByConditions()
          this.$message({
            message: msg,
            type: 'success'
          })
        } else {
          this.$message({
            message: '套餐状态修改失败',
            type: 'error'
          })
        }
      }).catch(err => {
        console.log(err)
        this.$message({
          message: '套餐状态修改失败',
          type: 'error'
        })
      })
    },
    // 批量删除
    batchDel () {
      this.$confirm('此操作将永久删除选中的套餐, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: this.baseSetmeal + '/setmeal-list',
          method: 'delete',
          data: this.setmealSelection
        }).then(res => {
          if (res.data.data) {
            this.searchSetmealByConditions()
            this.$message({
              message: '套餐批量删除成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: '套餐批量删除失败',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
          this.$message({
            message: '菜品批量删除失败',
            type: 'error'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 套餐上下架
    async updateStatus (row) {
      await request({
        url: this.baseSetmeal + `/status/${row.id}`,
        method: 'put'
      }).then(res => {
        if (res.data.data) {
          if (row.status === '启售') {
            this.$message({
              message: '菜品下架',
              type: 'success'
            })
          } else {
            this.$message({
              message: '菜品上架',
              type: 'success'
            })
          }
          this.searchSetmealByConditions()
        } else {
          this.$message({
            message: '菜品上下架失败',
            type: 'error'
          })
        }
      }).catch(err => {
        console.log(err)
        this.$message({
          message: '菜品上下架失败',
          type: 'error'
        })
      })
    },
    // 删除套餐
    delSetmeal (id) {
      this.$confirm('此操作将永久删除该套餐, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: this.baseSetmeal + `/setmeal-basic/${id}`,
          method: 'delete'
        }).then(res => {
          if (res.data.data) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.searchSetmealByConditions()
          } else {
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
          this.$message({
            message: '删除失败',
            type: 'error'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async handleSizeChange (val) {
      this.pageSize = val
      this.loading = true
      await this.searchSetmealByConditions()
    },
    async handleCurrentChange (val) {
      this.pageIndex = val
      this.loading = true
      await this.searchSetmealByConditions()
    },
    changeStatus (status) {
      this.SetmealStatus.forEach(item => {
        if (status === item.value) status = item.label
      })
      return status
    },
    changeCategory (categoryId) {
      if (this.categoryList) {
        this.categoryList.forEach(item => {
          if (categoryId === item.id) categoryId = item.categoryName
        })
      }
      return categoryId
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.searchCategoryListByType()
    this.searchSetmealByConditions()
    if (typeof this.$route.query.msg !== 'undefined') {
      this.$message.success(this.$route.query.msg)
    }
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style scoped>
  .setmeal {
    background-color: #fff;
    height: 690px;
    padding: 20px 20px;
    border-radius: 30px;
  }
  .el-table {
    margin-top: 20px;
  }

  .el-pagination {
    margin-top: 20px;
  }
</style>
